package com.edu.atams.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.atams.common.lang.Result;
import com.edu.atams.common.sheet.TeacherUpload;
import com.edu.atams.entity.SysUser;
import com.edu.atams.entity.Teacher;
import com.edu.atams.excel.ExcelListener;
import com.edu.atams.mapper.TeacherMapper;
import com.edu.atams.service.SysUserService;
import com.edu.atams.service.TeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author czj666
 * @since 2021-10-09
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    @Autowired
    TeacherService teacherService;
    @Autowired
    SysUserService sysUserService;
    public static <T> List<T> castList(Object obj, Class<T> clazz)
    {
        List<T> result = new ArrayList<T>();
        if(obj instanceof List<?>)
        {
            for (Object o : (List<?>) obj)
            {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }
    @Override
    public Result excelUpload(MultipartFile excel) throws IOException {
        String filename = excel.getOriginalFilename();
        // 对其上传的文件后缀进行判断是否为excel,其实还得判断类型和大小
        if (StrUtil.endWithIgnoreCase(filename,".xlsx") || StrUtil.endWithIgnoreCase(filename,".xls") ){
            InputStream inputStream = new BufferedInputStream(excel.getInputStream());
            ExcelListener teacherExcelListener = new ExcelListener();
            // 实例化ExcelReader,传入输入流和监听器，将其读取的每一条数据进行监听拦截处理,
            // 因为read方法读取之后，返回值为void没有任何操作，只负责读每一条数据，并转为指定类型，所以才用到监听器进行对每条数据进行保存
            ExcelReader excelReader = new ExcelReader(inputStream, null, teacherExcelListener);
            // 进去读取输入流对应的表，每读取一条数据，映射封装好，每一条数据都会跳到监听器的invoke方法进行处理
            excelReader.read(new Sheet(1,1, TeacherUpload.class));
            //excelListener接受object对象，所以接受数据时需要将object对象转换为指定的对象
            //castList将object对象进行转换
            List<TeacherUpload> data=castList(teacherExcelListener.getData(),TeacherUpload.class);
            return this.saveExcelData(data);
        }else{
            return Result.fail("不支持文件格式为xls或者xlsx以外的格式");
        }
    }

    @Override
    public Integer getAllNum() {
        List<Teacher> list = this.list();
        return list.size();
    }

    public Result saveExcelData(List<TeacherUpload> data){
        List<Teacher> teachers=new ArrayList<>();
        for(TeacherUpload teacherUpload:data){
            Teacher teacher=new Teacher();
            String schoolNo="";
            if(teacherUpload.getSex().equals("男")){
                teacher.setSex(0);
            }else if(teacherUpload.getSex().equals("女")){
                teacher.setSex(1);
            }else{
                return Result.fail("性别有误");
            }
            //生成唯一的工号
            do{
                schoolNo= RandomUtil.randomNumbers(6);
            }while(teacherService.count(new QueryWrapper<Teacher>().eq("schoolNo",teacher.getSchoolno()))!=0);
            teacher.setSchoolno(schoolNo);
            teacher.setBirthday(teacherUpload.getBirthday());
            teacher.setAddress(teacherUpload.getAddress());
            teacher.setTel(teacherUpload.getTel());
            teacher.setEmail(teacherUpload.getEmail());
            teacher.setIdCard(teacherUpload.getIcCard());
            teachers.add(teacher);
        }
        teacherService.saveBatch(teachers);
        for (Teacher teacher : teachers) {
            SysUser sysUser=new SysUser();
            //往用户表sysuer表中添加新增添的教师
            sysUser.setUsername(teacher.getSchoolno());
            sysUser.setPassword("123123");
            sysUser.setRoleType(2);
            sysUserService.save(sysUser);
            //生成sysuser对象获取到sysuser的id，添加到teacher表中user_id上
            teacher.setUserId(sysUser.getId());
            teacherService.updateById(teacher);
        }
        return Result.succ("");
    }
}
